<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">


  <meta name="msapplication-config" content="/images/browserconfig.xml">



  <meta name="keywords" content="前端">





  <link rel="alternate" href="/atom.xml" title="两万" type="application/atom+xml">






<meta name="description" content="树 tree 树（tree）是n（n&amp;gt;=0）个节点的有限集合。 当 n=0 时，称为空树 在任意一个非空树中有如下特点 有且仅有一个特定的称为 根（root） 的节点 当 n&amp;gt;1 时，其余节点可分为m（m&amp;gt;0）个互不相交的有限集，每一个集合本身又是一个树，称为根的 子树 节点的末端，叫做 叶子节点（leaf）     二叉树 binary tree 树的一种特殊结构 每个节点最多">
<meta name="keywords" content="js,html,css,node,javaScript,html5,css3,vue,canvas,前端,设计模式,后台,nginx">
<meta property="og:type" content="article">
<meta property="og:title" content="树">
<meta property="og:url" content="http://blog.bevexed.top/2019/05/15/树/index.html">
<meta property="og:site_name" content="两万">
<meta property="og:description" content="树 tree 树（tree）是n（n&amp;gt;=0）个节点的有限集合。 当 n=0 时，称为空树 在任意一个非空树中有如下特点 有且仅有一个特定的称为 根（root） 的节点 当 n&amp;gt;1 时，其余节点可分为m（m&amp;gt;0）个互不相交的有限集，每一个集合本身又是一个树，称为根的 子树 节点的末端，叫做 叶子节点（leaf）     二叉树 binary tree 树的一种特殊结构 每个节点最多">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://blog.bevexed.top/2019/05/15/树/tree.png">
<meta property="og:image" content="http://blog.bevexed.top/2019/05/15/树/each.png">
<meta property="og:updated_time" content="2019-06-13T09:53:11.864Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="树">
<meta name="twitter:description" content="树 tree 树（tree）是n（n&amp;gt;=0）个节点的有限集合。 当 n=0 时，称为空树 在任意一个非空树中有如下特点 有且仅有一个特定的称为 根（root） 的节点 当 n&amp;gt;1 时，其余节点可分为m（m&amp;gt;0）个互不相交的有限集，每一个集合本身又是一个树，称为根的 子树 节点的末端，叫做 叶子节点（leaf）     二叉树 binary tree 树的一种特殊结构 每个节点最多">
<meta name="twitter:image" content="http://blog.bevexed.top/2019/05/15/树/tree.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.bevexed.top/2019/05/15/树/">





  <title>树 | 两万</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?4fdb363593835184af3e5b1a4874f9db";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">两万</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Daily</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.bevexed.top/2019/05/15/树/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="两万">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/IMG_2021.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="两万">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">树</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-15T17:11:36+08:00">
                2019-05-15
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/算法/" itemprop="url" rel="index">
                    <span itemprop="name">算法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/05/15/树/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/05/15/树/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2019/05/15/树/" class="leancloud_visitors" data-flag-title="树">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="树-tree"><a href="#树-tree" class="headerlink" title="树 tree"></a>树 tree</h1><ul>
<li>树（tree）是n（n&gt;=0）个节点的有限集合。</li>
<li>当 n=0 时，称为空树</li>
<li>在任意一个非空树中有如下特点<ul>
<li>有且仅有一个特定的称为 <strong>根（root）</strong> 的节点</li>
<li>当 n&gt;1 时，其余节点可分为m（m&gt;0）个互不相交的有限集，每一个集合本身又是一个树，称为根的 <strong>子树</strong></li>
<li>节点的末端，叫做 <strong>叶子节点（leaf）</strong></li>
</ul>
</li>
</ul>
<p><img src="tree.png" alt="例图"></p>
<h2 id="二叉树-binary-tree"><a href="#二叉树-binary-tree" class="headerlink" title="二叉树 binary tree"></a>二叉树 binary tree</h2><ul>
<li>树的一种特殊结构</li>
<li>每个节点最多有两个子节点</li>
<li>二叉树节点的两个孩子节点，一个被称为 <strong>左孩子（left child）</strong>，一个被称为 <strong>右孩子（right child）</strong><ul>
<li>这两个孩子顺序固定，不可颠倒</li>
</ul>
</li>
<li>存储结构<ul>
<li>链式存储结构</li>
<li>数组</li>
</ul>
</li>
</ul>
<h3 id="满二叉树"><a href="#满二叉树" class="headerlink" title="满二叉树"></a>满二叉树</h3><ul>
<li>一个二叉树的所有非叶子节点都存在左右孩子</li>
<li>所有叶子节点都在同一层级上</li>
</ul>
<h3 id="完全二叉树"><a href="#完全二叉树" class="headerlink" title="完全二叉树"></a>完全二叉树</h3><ul>
<li>对一个有 n 个节点的二叉树，按层级顺序编号，则所有节点的编号为从 1 到 n 。如果这个树所有节点和同样深度的满二叉树的编号为从 1 到 n 的节点位置相同，则这个二叉树为完全二叉树</li>
</ul>
<h3 id="二叉查找树"><a href="#二叉查找树" class="headerlink" title="二叉查找树"></a>二叉查找树</h3><ul>
<li>也叫二叉排序树</li>
<li>如果左子树不为空，则左子树上所有节点的值均小于根节点的值</li>
<li>如果右子树不为空，则右子树上所有节点的值均大于根节点的值</li>
<li>左右子树也是二叉树查找</li>
<li>对于一个 <strong>节点分布相对均衡</strong> 的二叉查找树来说，如果节点总数是 <strong>n</strong>，那么搜索节点的时间复杂度为 <strong>O(logn)</strong>,和数的深度一样</li>
<li>二叉树的自平衡</li>
</ul>
<h3 id="二叉树与存储结构"><a href="#二叉树与存储结构" class="headerlink" title="二叉树与存储结构"></a>二叉树与存储结构</h3><h4 id="链式存储结构"><a href="#链式存储结构" class="headerlink" title="链式存储结构"></a>链式存储结构</h4><p>二叉树的每一个节点由三部分组成</p>
<ul>
<li>存储数据的 data 变量</li>
<li>指向左孩子的 left 指针</li>
<li>指向右孩子的 right 指针</li>
</ul>
<h4 id="数组存储结构"><a href="#数组存储结构" class="headerlink" title="数组存储结构"></a>数组存储结构</h4><ul>
<li>按照层级顺序把二叉树的节点放到数组的对应位置上</li>
<li>如果某一节点的左孩子或右孩子空缺，则数组的相应位置也空出来</li>
<li>假设一个父节点的下标为 <strong>parent</strong>，那么它的左孩子的下标为 <strong>2 * parent + 1</strong>，它的右孩子的下标为 <strong>2 * parent + 2</strong></li>
<li>假设一个左孩子的下标为 <strong>leftChilde</strong> ，那么他的父节点的下标为 <strong>(leftChild - 1) / 2</strong></li>
</ul>
<h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3><h4 id="二叉查找树（binary-search-tree）"><a href="#二叉查找树（binary-search-tree）" class="headerlink" title="二叉查找树（binary search tree）"></a>二叉查找树（binary search tree）</h4><p>二叉查找树在二叉树的基础上增加了以下条件</p>
<ul>
<li>如果左子树不为空，则左子树上所有节点的值均小于根节点的值</li>
<li>如果右子树不为空，则右子树上所有节点的值均大于根节点的值</li>
<li>左右子叶也是二叉树查找</li>
<li>时间复杂度 O(logn), n 为树的深度</li>
</ul>
<h4 id="维持相对顺序"><a href="#维持相对顺序" class="headerlink" title="维持相对顺序"></a>维持相对顺序</h4><ul>
<li>二叉查找树的左子树小于父节点，右子树大于父节点，保证了二叉树的有序性</li>
</ul>
<h3 id="二叉树遍历"><a href="#二叉树遍历" class="headerlink" title="二叉树遍历"></a>二叉树遍历</h3><p>将 <strong>非线性的数据结构</strong> 转换成 <strong>线性的序列</strong></p>
<h4 id="深度优先遍历-demo"><a href="#深度优先遍历-demo" class="headerlink" title="深度优先遍历 (demo)"></a>深度优先遍历 (<a href="demo.html">demo</a>)</h4><p>偏向于深度，<strong>一头扎到底</strong>的访问方式</p>
<h5 id="前序遍历（DLR"><a href="#前序遍历（DLR" class="headerlink" title="前序遍历（DLR)"></a>前序遍历（DLR)</h5><ul>
<li>过程</li>
</ul>
<ol>
<li>先访问 <strong>根节点</strong></li>
<li>遍历 <strong>左子树</strong></li>
<li>遍历 <strong>右子树</strong></li>
</ol>
<ul>
<li>结果 : ABDECF</li>
</ul>
<h5 id="中序遍历（LDR）"><a href="#中序遍历（LDR）" class="headerlink" title="中序遍历（LDR）"></a>中序遍历（LDR）</h5><ul>
<li>过程<br>左 根 右</li>
<li>结果 : DBEACF</li>
</ul>
<h5 id="后序遍历（LRD）"><a href="#后序遍历（LRD）" class="headerlink" title="后序遍历（LRD）"></a>后序遍历（LRD）</h5><ul>
<li>过程<br>左 右 根</li>
<li>结果 ： DEBFCA</li>
</ul>
<h5 id="demo"><a href="#demo" class="headerlink" title="demo"></a>demo</h5><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Binary Tree<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="css">    <span class="selector-class">.root</span> &#123;</span></span><br><span class="line"><span class="undefined">      display: flex;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">border</span>: 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-id">#000</span>;</span></span><br><span class="line"><span class="undefined">      width: 600px;</span></span><br><span class="line"><span class="undefined">      margin: 0 auto;</span></span><br><span class="line"><span class="undefined">      height: 150px;</span></span><br><span class="line"><span class="undefined">      align-items: center;</span></span><br><span class="line"><span class="undefined">      justify-content: center;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="css">    <span class="selector-class">.root</span> <span class="selector-tag">div</span> &#123;</span></span><br><span class="line"><span class="undefined">      display: flex;</span></span><br><span class="line"><span class="undefined">      height: 70%;</span></span><br><span class="line"><span class="undefined">      width: 44%;</span></span><br><span class="line"><span class="undefined">      margin: 0 3%;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">border</span>: 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-id">#000</span>;</span></span><br><span class="line"><span class="undefined">      justify-content: center;</span></span><br><span class="line"><span class="undefined">      align-items: center;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-id">#fff</span>;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined">  </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"root"</span>&gt;</span></span><br><span class="line">  1</span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span>&gt;</span>2</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>4<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>5<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span>&gt;</span>3</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>6<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>7<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="undefined">  /**</span></span><br><span class="line"><span class="undefined">   * 深度优先遍历的递归写法</span></span><br><span class="line"><span class="undefined">   * 原理：递归的回溯性</span></span><br><span class="line"><span class="undefined">   */</span></span><br><span class="line"><span class="actionscript">  <span class="class"><span class="keyword">class</span> <span class="title">TravelTree</span> </span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">constructor</span>() &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.nodeList = [];</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    preOrder = <span class="function"><span class="params">node</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (node) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.nodeList.push(node.firstChild.textContent.trim());</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.preOrder(node.firstElementChild);</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.preOrder(node.lastElementChild);</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    inOrder = <span class="function"><span class="params">node</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (node) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.inOrder(node.firstElementChild);</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.nodeList.push(node.firstChild.textContent.trim());</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.inOrder(node.lastElementChild);</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    postOrder = <span class="function"><span class="params">node</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (node) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.postOrder(node.firstElementChild);</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.postOrder(node.lastElementChild);</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.nodeList.push(node.firstChild.textContent.trim());</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    reset() &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.nodeList = [];</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">  <span class="keyword">let</span> node = <span class="built_in">document</span>.querySelector(<span class="string">'.root'</span>);</span></span><br><span class="line"><span class="javascript">  <span class="keyword">let</span> tree = <span class="keyword">new</span> TravelTree();</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">'TravelTree'</span>);</span></span><br><span class="line"><span class="undefined">  tree.reset();</span></span><br><span class="line"><span class="undefined">  tree.preOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(tree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  tree.reset();</span></span><br><span class="line"><span class="undefined">  tree.inOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(tree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  tree.reset();</span></span><br><span class="line"><span class="undefined">  tree.postOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(tree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">  <span class="comment">// 深度优先遍历的非递归写法</span></span></span><br><span class="line"><span class="actionscript">  <span class="class"><span class="keyword">class</span> <span class="title">StackTree</span> </span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">constructor</span>() &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.nodeList = [];</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.stack = []</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    preOrder(node) &#123;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> treeNode = node;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">while</span> (treeNode || <span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">// 进栈 将所有左节点压栈</span></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">while</span> (treeNode) &#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.stack.push(treeNode);</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.nodeList.push(treeNode.firstChild.textContent.trim());</span></span><br><span class="line"><span class="undefined">          treeNode = treeNode.firstElementChild;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">// 出栈</span></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (<span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="actionscript">          treeNode = <span class="keyword">this</span>.stack.pop();</span></span><br><span class="line"><span class="undefined">          treeNode = treeNode.lastElementChild;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    inOrder(node) &#123;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> treeNode = node;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">while</span> (treeNode || <span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">while</span> (treeNode) &#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.stack.push(treeNode);</span></span><br><span class="line"><span class="undefined">          treeNode = treeNode.firstElementChild;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (<span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="actionscript">          treeNode = <span class="keyword">this</span>.stack.pop();</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.nodeList.push(treeNode.firstChild.textContent.trim());</span></span><br><span class="line"><span class="undefined">          treeNode = treeNode.lastElementChild;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    /*</span></span><br><span class="line"><span class="undefined">    *  将根节点压入第一个栈</span></span><br><span class="line"><span class="undefined">    *  从第一个栈中弹出一个元素，压入第二个栈</span></span><br><span class="line"><span class="undefined">    *  然后分别将该节点的左右孩子压入第一个栈</span></span><br><span class="line"><span class="undefined">    *  重复步骤2和步骤3直到第一个栈为空</span></span><br><span class="line"><span class="undefined">    *  执行结束，第二个栈中就保存了所有节点的后序遍历输出结果。依次将元素从第二个栈中弹出即可。</span></span><br><span class="line"><span class="undefined">    */</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    postOrder(node) &#123;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> treeNode = node;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.stack.push(treeNode);</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">while</span> (<span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="actionscript">        treeNode = <span class="keyword">this</span>.stack.pop();</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.nodeList.unshift(treeNode.firstChild.textContent.trim());</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (treeNode.firstElementChild) &#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.stack.push(treeNode.firstElementChild)</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (treeNode.lastElementChild) &#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.stack.push(treeNode.lastElementChild)</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined">    </span></span><br><span class="line"><span class="actionscript">    <span class="comment">// todo: 单个栈的实现方法</span></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    reset() &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.stack = [];</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.nodeList = [];</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">  <span class="keyword">let</span> stackTree = <span class="keyword">new</span> StackTree();</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">'stackTree'</span>);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  stackTree.preOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(stackTree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  stackTree.reset();</span></span><br><span class="line"><span class="undefined">  stackTree.inOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(stackTree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">  stackTree.reset();</span></span><br><span class="line"><span class="undefined">  stackTree.postOrder(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(stackTree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">  <span class="comment">// 广度度优先遍历非递归</span></span></span><br><span class="line"><span class="actionscript">  <span class="class"><span class="keyword">class</span> <span class="title">WidthTravelTree</span> </span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">constructor</span>() &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.nodeList = [];</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.stack = []</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">    <span class="comment">// 队列</span></span></span><br><span class="line"><span class="undefined">    widthTravel(node) &#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (node) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.stack.push(node);</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.nodeList.push(node.firstChild.textContent.trim());</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">while</span> (<span class="keyword">this</span>.stack.length) &#123;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">let</span> item = <span class="keyword">this</span>.stack.shift();</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">if</span> (item.firstElementChild) &#123;</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">this</span>.nodeList.push(item.firstElementChild.firstChild.textContent.trim());</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">this</span>.stack.push(item.firstElementChild);</span></span><br><span class="line"><span class="undefined">          &#125;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">if</span> (item.lastElementChild) &#123;</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">this</span>.nodeList.push(item.lastElementChild.firstChild.textContent.trim());</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">this</span>.stack.push(item.lastElementChild)</span></span><br><span class="line"><span class="undefined">          &#125;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined">  &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">'WidthTravelTree'</span>);</span></span><br><span class="line"><span class="javascript">  <span class="keyword">let</span> widthTravelTree = <span class="keyword">new</span> WidthTravelTree();</span></span><br><span class="line"><span class="undefined">  widthTravelTree.widthTravel(node);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(widthTravelTree.nodeList);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="广度优先遍历"><a href="#广度优先遍历" class="headerlink" title="广度优先遍历"></a>广度优先遍历</h4><ul>
<li>层序遍历<br><img src="each.png" alt="图">  </li>
</ul>
<h2 id="资料参考"><a href="#资料参考" class="headerlink" title="资料参考"></a>资料参考</h2><ul>
<li><a href="https://blog.51cto.com/9291927/2068745" target="_blank" rel="noopener">图片来源</a></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/14/数据结构基础/" rel="next" title="数据结构基础">
                <i class="fa fa-chevron-left"></i> 数据结构基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/06/10/树/demo/" rel="prev" title="">
                 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/IMG_2021.jpg" alt="两万">
            
              <p class="site-author-name" itemprop="name">两万</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/bevexed" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://cn.vuejs.org/" title="Vue" target="_blank">Vue</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bevexed.top/frontEnd/H5_Daily/canvas/demo/FlappyBird" title="FlapBird" target="_blank">FlapBird</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#树-tree"><span class="nav-text">树 tree</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树-binary-tree"><span class="nav-text">二叉树 binary tree</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#满二叉树"><span class="nav-text">满二叉树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#完全二叉树"><span class="nav-text">完全二叉树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二叉查找树"><span class="nav-text">二叉查找树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二叉树与存储结构"><span class="nav-text">二叉树与存储结构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#链式存储结构"><span class="nav-text">链式存储结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数组存储结构"><span class="nav-text">数组存储结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#应用"><span class="nav-text">应用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#二叉查找树（binary-search-tree）"><span class="nav-text">二叉查找树（binary search tree）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#维持相对顺序"><span class="nav-text">维持相对顺序</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二叉树遍历"><span class="nav-text">二叉树遍历</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#深度优先遍历-demo"><span class="nav-text">深度优先遍历 (demo)</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#前序遍历（DLR"><span class="nav-text">前序遍历（DLR)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#中序遍历（LDR）"><span class="nav-text">中序遍历（LDR）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#后序遍历（LRD）"><span class="nav-text">后序遍历（LRD）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#demo"><span class="nav-text">demo</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#广度优先遍历"><span class="nav-text">广度优先遍历</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#资料参考"><span class="nav-text">资料参考</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">两万</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">26.6k</span>
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.bevexed.top/2019/05/15/树/';
          this.page.identifier = '2019/05/15/树/';
          this.page.title = '树';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: true,
        appId: 'EoJiOrKeNWgSwq0eXmK0VK7V-gzGzoHsz',
        appKey: 'H1riqYCRgB88YzWIOinxfaAg',
        placeholder: '说点啥吧......',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EoJiOrKeNWgSwq0eXmK0VK7V-gzGzoHsz", "H1riqYCRgB88YzWIOinxfaAg");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
